<template>
  <div class='app-container'>
    <div class='app-box clear'>
        <div class='inputbox'>
            <div class="day-top clearfix">
              <div class="top">
                <span>出单时间：</span>
                <el-date-picker
                  class='wd93'
                  v-model="time1"
                  value-format="yyyy-MM"
                  type="month"
                  size='mini'
                  clearable
                  prefix-icon=' '
  
                  placeholder="选择月">
                </el-date-picker>
                  <span>至</span>
                <el-date-picker
                  class='wd93'
                  v-model="time2"
                  value-format="yyyy-MM"
                  type="month"
                  size='mini'
                  clearable
                  prefix-icon=' '
          
                  placeholder="选择月">
                </el-date-picker>
              </div>
              <div class="top3">
                <span>所属机构：</span>
                <!-- <ztree-select class="wd210" v-model="organizationUnitId" :treedata="treeData" :childprops="childprops" @change='setSelectedId'></ztree-select> -->
                <el-select v-model="organizationUnitId" placeholder="请选择" size="mini" style="width:175px;" multiple collapse-tags>
                  <el-option
                    v-for="item in treeData"
                    :key="item.organizationId"
                    :label="item.organizationName"
                    :value="item.organizationId">
                  </el-option>
                </el-select>
              </div>
              <div class="top2">
                <span>保险公司：</span>
                 <el-select  class="wd130" size="mini" v-model="Insurance" placeholder="请选择保险公司" >
                  <el-option-group v-for="group in companies" :key="group.letter" :label="group.letter">
                    <el-option v-for="item in group.insurances" :key="item.id" :label="item.insuranceName" :value="item.id">
                    </el-option>
                  </el-option-group>
                </el-select>
              </div>
               <!-- <div class="top2">
                <span>数据类型：</span>
                   <el-select v-model="value5" class="wd130" size="mini"  placeholder="请选择">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
              </div> -->
              <el-dropdown split-button type="primary" @click="toSearch" size="mini" style="height:29px;" placement='bottom-end' class="day-dropdown"  @command='exportForm'>
                查询
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item style="width:87px; text-align:center;">导出</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
             </div>
             <!-- <div class="unitbox"><span>(单位：万元)</span></div> -->
              <div class="cenVal">
              <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                  {{allSelect}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="1">保单量</el-dropdown-item>
                  <el-dropdown-item command="2">总保费（万元）</el-dropdown-item>
                  <el-dropdown-item command="3">净保费（万元）</el-dropdown-item>
                  <el-dropdown-item command="4">总收入（万元）</el-dropdown-item>
                  <el-dropdown-item command="5">总支出（万元）</el-dropdown-item>
                  <el-dropdown-item command="6">利润（万元）</el-dropdown-item>
                  <el-dropdown-item command="7">利润率（百分比）</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
             <!-- 列表 -->
            <div class="pday-table pzday-table">
              <el-table
                :data="tableData3"
                header-align="left"
                align="right"
                 stripe
                type="index"
                v-loading="loading"
                style="width: 100%" >
                <el-table-column
                  fixed
                  align="center"
                 :render-header="renderHeader"
                  width="130">
                   <template slot-scope="scope">
                     <span @click="toMonthForm(scope.row.id)" style="cursor:pointer;" class="ishover">{{scope.row.displayName}}</span>
                   </template>
                </el-table-column>
            
                  <el-table-column 
                 align="center"
                  v-for="(col,index) in columns"
                  :key="col.value"
                  :prop="col.value" 
                  :label="col.value"
                  min-width="100px">
                   <el-table-column
                        v-for="(item,indexItem) in col.items"
                        :key="item"
                        :prop="item" 
                        :label="item"
                         min-width="100px"
                        align="right">
                   <template slot-scope="scope">

                     <div :ref="'allTd'+col.value+item | format">
                        <span v-for="(obj,newindex) in month"  style="display:block">
                         
                    <span v-if="obj == item" >
                       <el-popover trigger="click" class="item" placement="bottom">
                  <div class='compony_text'>
                     <div class="baofe1">
                        <div class="baofeiDetail">
                        <div class="wd70" style="text-align:right">保单量:</div>
                        <div class="wd120" style="text-align:left">{{scope.row.values[newindex].guaranteeSlipCount}}</div>
                      </div>
                    </div>
                    <div class="baofe1">
                      <div class="baofeiDetail">
                        <div class="wd70" style="text-align:right">总保费:</div>
                        <div class="wd120" style="text-align:left">{{scope.row.values[newindex].totalPremium | keepTwoNum}}</div>
                      </div>
                      <div class="baofeiDetail">
                        <div class="wd70" style="text-align:right">净保费:</div>
                        <div class="wd120" style="text-align:left">{{scope.row.values[newindex].totalNetPremium | keepTwoNum}}</div>
                      </div>
                    </div>
                    <div class="baofe1">
                      <div class="baofeiDetail">
                        <div class="wd70" style="text-align:right">总收入:</div>
                        <div class="wd120" style="text-align:left">{{scope.row.values[newindex].incomes | keepTwoNum}}</div>
                      </div>
                      <div class="baofeiDetail">
                        <div class="wd70" style="text-align:right">总支出:</div>
                        <div class="wd120" style="text-align:left">{{scope.row.values[newindex].expends | keepTwoNum}}</div>
                      </div>
                    </div>
                    <div class="baofe1">
                      <div class="baofeiDetail">
                        <div class="wd70" style="text-align:right">利润:</div>
                        <div class="wd120" style="text-align:left">{{scope.row.values[newindex].profit | keepTwoNum}}</div>
                      </div>
                      <div class="baofeiDetail">
                        <div class="wd70" style="text-align:right">百分比:</div>
                        <div class="wd120" style="text-align:left">{{((scope.row.values[newindex].profitRate*100).toFixed(2))}}%</div>
                      </div>
                    </div>
                    <div class="baofe1" style="text-align:center;overflow:hidden;">
                      <a @click="toDayForm(scope.row.insuranceId,item,col)">查看更多</a>
                    </div>
                  </div>
        
                       <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 1 && scope.row.values[newindex].guaranteeSlipCount != null">{{scope.row.values[newindex].guaranteeSlipCount}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 2 && scope.row.values[newindex].totalPremium != null">{{scope.row.values[newindex].totalPremium | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 3 && scope.row.values[newindex].totalNetPremium != null">{{scope.row.values[newindex].totalNetPremium | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 4 && scope.row.values[newindex].incomes != null">{{scope.row.values[newindex].incomes | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 5 && scope.row.values[newindex].expends != null">{{scope.row.values[newindex].expends | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 6 && scope.row.values[newindex].profit != null">{{scope.row.values[newindex].profit | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 7 && scope.row.values[newindex].profitRate != null" >{{((scope.row.values[newindex].profitRate*100).toFixed(2))}}%</span>
                </el-popover>
                        
                    </span>
                  </span>
               
                        <span v-for="(obj,newindex) in month">
                          <!-- <span>{{item}}</span> -->
                          <span v-if="obj == item">
                              <span v-if="value5 == 1 && scope.row.values[newindex].guaranteeSlipCount == null">-</span>
                              <span v-if="value5 == 2 && scope.row.values[newindex].totalPremium == null" >-</span>
                            <span v-if="value5 == 3 && scope.row.values[newindex].totalNetPremium == null">-</span>
                            <span v-if="value5 == 4 && scope.row.values[newindex].incomes == null">-</span>
                            <span v-if="value5 == 5 && scope.row.values[newindex].expends == null">-</span>
                            <span v-if="value5 == 6 && scope.row.values[newindex].profit == null">-</span>
                            <span v-if="value5 == 7 && scope.row.values[newindex].profitRate == null">-</span>
                            <!-- {{scope.row.values[newindex]?scope.row.values[newindex].totalPremium:'-'}} -->
                          </span>
                        </span>
                        <!-- <span class="companytest"></span> -->
                     </div>
                  </template>
                  </el-table-column>
                </el-table-column>
                    <el-table-column
                  prop="total"
                  align="center"
                  label="合计"
                  fixed="right"
                 >
                   <template slot-scope="scope">
                      <el-popover trigger="click" class="item"  placement="bottom" >
                        <div  class='compony_text' v-if="scope.row.total != null">
                          <div class="baofe1">
                              <div class="baofeiDetail">
                                <div class="wd70" style="text-align:right">保单量:</div>
                                <div class="wd120" style="text-align:left">{{scope.row.total.guaranteeSlipCount}}</div>
                              </div>
                            </div>
                            <div class="baofe1">
                              <div class="baofeiDetail">
                                <div class="wd70" style="text-align:right;">总保费:</div>
                                <div class="wd120" style="text-align:left;">{{scope.row.total.totalPremium | keepTwoNum}}</div>
                              </div>
                              <div class="baofeiDetail">
                                <div class="wd70" style="text-align:right;">净保费:</div>
                                <div class="wd120" style="text-align:left;">{{scope.row.total.totalNetPremium | keepTwoNum}}</div>
                              </div>
                            </div>
                             <div class="baofe1">
                               <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right;">总收入:</div>
                                  <div class="wd120" style="text-align:left;">{{scope.row.total.incomes | keepTwoNum}}</div>
                                </div>
                                <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right;">总支出:</div>
                                  <div class="wd120" style="text-align:left;">{{scope.row.total.expends | keepTwoNum}}</div>
                                </div>
                             </div>
                             <div class="baofe1">
                                <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right">利润:</div>
                                  <div class="wd120" style="text-align:left">{{scope.row.total.profit | keepTwoNum}}</div>
                                </div>
                                <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right">百分比:</div>
                                  <div class="wd120" style="text-align:left">{{((scope.row.total.profitRate*100).toFixed(2))}}%</div>
                                </div>
                             </div>
                              <div class="baofe1" style="text-align:center;overflow:hidden;">
                                <a @click="toMonthForm(scope.row.id)">查看更多</a>
                              </div>
                        </div>
                        <div  class='compony_text' style="text-align:center;overflow:hidden;" v-else>
                          暂无数据
                        </div>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 1 && scope.row.total.guaranteeSlipCount !=null">{{scope.row.total.guaranteeSlipCount}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 2 && scope.row.total.totalPremium !=null">{{scope.row.total.totalPremium | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 3 && scope.row.total.totalNetPremium !=null">{{scope.row.total.totalNetPremium | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 4 && scope.row.total.incomes !=null">{{scope.row.total.incomes | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 5 && scope.row.total.expends !=null">{{scope.row.total.expends | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 6 && scope.row.total.profit !=null">{{scope.row.total.profit | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 7 && scope.row.total.profitRate !=null">{{((scope.row.total.profitRate*100).toFixed(2))}}%</span>
                          <!-- {{scope.row.total}} -->
                       </el-popover>
                       <span v-if="value5 == 1 && scope.row.total.guaranteeSlipCount == null">-</span>
                      <span v-if="value5 == 2 && scope.row.total.totalPremium == null">-</span>
                      <span v-if="value5 == 3 && scope.row.total.totalNetPremium == null">-</span>
                      <span v-if="value5 == 4 && scope.row.total.incomes == null">-</span>
                      <span v-if="value5 == 5 && scope.row.total.expends == null">-</span>
                      <span v-if="value5 == 6 && scope.row.total.profit == null" >-</span>
                      <span v-if="value5 == 7 && scope.row.total.profitRate== null">-</span>
                  </template>
                </el-table-column>
              </el-table>
            </div> 
        </div>
    </div>
</template>
<script>
import ztreeSelect from "@/components/z-select/index.vue";
export default {
  components: {
    ztreeSelect
  },
  filters: {
    keepTwoNum: function(val) {
      val = Number(val);
      return val.toFixed(2);
    },
    format: function(val) {
      val = val.replace("年", "y");
      val = val.replace("月", "m");
      return val;
    }
  },
  data() {
    return {
      time1: "",
      time2: "",
      endDateOpt: this.enddate(),
      startDateOpt: this.startdate(),
      companies: [],
      treeData: [],
      //数组子级相关参数
      childprops: {
        name: "displayName", //显示名字
        children: "organizationUnits", //子级字段名
        lv: "level" //当前层级
      },
      organizationUnitId: [],
      type1: "0",
      Insurance: "",
      loading: false,
      //数据类型选项1
      allSelect: "总保费",
       options: [
        {
          value: "1",
          label: "保单量"
        },
        {
          value: "2",
          label: "总保费"
        },
        {
          value: "3",
          label: "净保费"
        },
        {
          value: "4",
          label: "总收入"
        },
        {
          value: "5",
          label: "总支出"
        },
        {
          value: "6",
          label: "利润"
        },
        {
          value: "7",
          label: "利润率"
        }
      ],
      value5: '2',

      //列表数据
      tableData3: []
      //列表合计详情
    };
  },
  mounted() {
    this.getCompanies();
    this.getUnits();
    // let a = this.formatDate(new Date().getTime(),0);
    let a = new Date().getFullYear() + "-12";
    // this.time2 = a.substring(0,7);
    this.time2 = a;
    let b = new Date().getFullYear() + "-01";
    // let b = this.formatDate(new Date().getTime(),1);
    this.time1 = b;
    if (this.$route.query.beginDate || this.$route.query.endDate) {
      this.time1 = this.$route.query.beginDate;
      this.time2 = this.$route.query.endDate;
      if (this.$route.query.insuranceId) {
        //Insurance
        this.Insurance = this.$route.query.insuranceId;
        console.log(this.Insurance);
      }
      if (
        this.$route.query.organizationIds &&
        typeof this.$route.query.organizationIds == "string"
      ) {
        //organizationId
        console.log(1);
        let arr = [];
        //  console.log()
        //  this.$route.query.organizationIds =Number(this.$route.query.organizationIds)
        arr.push(Number(this.$route.query.organizationIds));
        this.organizationUnitId = arr;
      } else {
        console.log(2);

        for (let i = 0; i < this.$route.query.organizationIds.length; i++) {
          this.$route.query.organizationIds[i] = Number(
            this.$route.query.organizationIds[i]
          );
        }
        this.organizationUnitId = this.$route.query.organizationIds;
      }
      // this.value5 = this.$route.query.queryData;
    }
    this.getFirstData();
  },
  computed: {},
  watch: {
    $route(to, from) {
      this.time1 = this.$route.query.beginDate;
      this.time2 = this.$route.query.endDate;
      if (this.$route.query.insuranceId) {
        //Insurance
        this.Insurance = this.$route.query.insuranceId;
        console.log(this.Insurance);
      }
      if (this.$route.query.organizationIds) {
        //organizationId
        this.organizationUnitId = this.$route.query.organizationIds;
      }
      // this.value5 = this.$route.query.queryData;
      this.getFirstData();
    }
  },
  created() {
    this.geshiTable();
  },
  methods: {
    geshiTable() {
      let that = this;
      setTimeout(function() {
        //  console.log(that.$refs)
        let tdObj = that.$refs;
        for (let k in tdObj) {
          if (
            k.substring(12) == "3m" ||
            k.substring(12) == "6m" ||
            k.substring(12) == "9m" ||
            k.substring(12) == "12m"
          ) {
            let aa = tdObj[k];
            for (let i = 0; i < aa.length; i++) {
              // console.log(aa[i])
              aa[i].parentNode.parentNode.style.borderRight =
                "1px solid #aeaeae";
            }
          }
        }
      }, 10);
    },
    handleCommand(command) {
      this.value5 = command;
      this.allSelect = this.options[command - 1].label;
    },
    renderHeader(h, { column, $index }) {
      return (
        <div class="thHead">
          <span style="left:56px;">&nbsp;&nbsp;月份&nbsp;&nbsp;</span>
          <span style="left:-15px;">组织机构</span>
        </div>
      );
    },
    //开始时间
    startdate() {
      var that = this;
      return {
        disabledDate(time) {
          if (that.time2 != "") {
            return time.getTime() > new Date(that.time2).getTime();
          }
        }
      };
    },
    //结束时间
    enddate() {
      var that = this;
      return {
        disabledDate(time) {
          return time.getTime() < new Date(that.time1).getTime();
        }
      };
    },
    // 格式化
    formatDate(time, mon) {
      var date = new Date(time);

      var year = date.getFullYear() - mon,
        month = date.getMonth() + 1, //月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
      var newTime =
        year +
        "-" +
        (month < 10 ? "0" + month : month) +
        "-" +
        (day < 10 ? "0" + day : day) +
        " " +
        (hour < 10 ? "0" + hour : hour) +
        ":" +
        (min < 10 ? "0" + min : min) +
        ":" +
        (sec < 10 ? "0" + sec : sec);
      return newTime;
    },
    // 公司
    getCompanies() {
      let that = this;
      let all = {
        letter: "",
        insurances: [{ insuranceName: "全部保险公司", id: "" }]
      };
      let params = {};
      this.post(params, "services/app/common/GetGroupInsurances").then(rs => {
        console.log(rs);
        if (rs.success) {
          let result = rs.result.items;
          result.unshift(all);
          that.companies = result;
        }
      });
    },
    // 机构
    getUnits() {
      let params = {};
      this.post(params, "services/app/common/ChildOrganizations").then(rs => {
        console.log(rs);
        if (rs.success) {
          this.treeData = rs.result;
        }
      });
    },
    // setSelectedId(val) {
    //   this.organizationUnitId = val;
    // },
    getFirstData() {
      this.loading = true;
      let params = {
        beginDate: this.time1,
        endDate: this.time2,
        organizationIds: this.organizationUnitId,
        insuranceId: this.Insurance,
        queryData: this.value5
      };
      this.post(params, "services/app/report/Organization_Months").then(rs => {
        if (rs.success) {
          // this.tableData3 = rs.result.item;·
          this.columns = rs.result.columns;
          this.loading = false;
          this.geshiTable();
          let arr = [];
          rs.result.columns.map(function(item) {
            arr = arr.concat(item.items);
          });
          this.month = arr;
          if (rs.result.item.length < 6) {
            // console.log('-----sad------')
            // console.log(arr.length)
            let values = [];
            for (let i = 0; i < arr.length; i++) {
              values.push({
                totalPremium: null,
                totalNetPremium: null,
                incomes: null,
                expends: null,
                profit: null,
                profitRate: null
              });
            }
            let bbVal = [];
            for (let j = 0; j < rs.result.item.length; j++) {
              bbVal.push(rs.result.item[j]);
            }
            for (let k = 0; k < 6 - rs.result.item.length; k++) {
              let total = {
                totalPremium: null,
                totalNetPremium: null,
                incomes: null,
                expends: null,
                profit: null,
                profitRate: null
              };

              bbVal.push({
                insuranceId: "",
                insuranceName: "",
                total: total,
                values: values
              });
            }
            this.tableData3 = bbVal;
          } else {
            this.tableData3 = rs.result.item;
          }
        } else {
          this.loading = false;
          this.$notify.error({
            title: "错误",
            message: rs.error.message
          });
        }
      });
    },
    // 搜索
    toSearch() {
      if (this.time1 != null && this.time2 != null) {
        this.$router.push({
          name: "zmonthform",
          query: {
            beginDate: this.time1,
            endDate: this.time2,
            organizationIds: this.organizationUnitId,
            insuranceId: this.Insurance,
            queryData: this.value5,
            time: new Date().getTime()
          }
        });
      } else {
        this.$message.error("请输入出单时间");
      }
    },
    //导出
    exportForm() {
      let params = {
        beginDate: this.time1,
        endDate: this.time2,
        organizationIds: this.organizationUnitId,
        insuranceId: this.Insurance,
        queryData: this.value5
      };
      this.post(params, "services/app/report/Organization_Months_Export").then(
        rs => {
          if (rs.success) {
            let filePath = rs.result.filePath;
            console.log(filePath);
            window.location.href = filePath;
          } else {
            this.loading = false;
            this.$notify.error({
              title: "错误",
              message: rs.error.message
            });
          }
        }
      );
    },
    toexport() {},
    //跳转到日报表
    toDayForm(id, date, col) {
      //  console.log(ins)
      //  date = date.slice(0,-1);
      //  console.log(date);
      //  var T = new Date();
      //  var year = T.getFullYear();
      //  var time = year+'-'+date;
      var mon =
        Number(date.replace("月", "")) > 9
          ? Number(date.replace("月", ""))
          : "0" + Number(date.replace("月", ""));
      var mon2 = col.value.substring(0, 4) + "-" + mon;
      this.$router.push({
        name: "dayform",
        query: { month: mon2, org: id }
      });
    },
    toMonthForm(id) {
      console.log(id);
      this.$router.push({
        name: "monthform",
        query: { beginDate: this.time1, endDate: this.time2, org: id }
      });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss"  scoped>
.ishover:hover {
  // color:red;
  font-weight: 600;
  border-bottom: 1px dotted #333;
}
.wd60 {
  width: 60px;
}
.wd70 {
  width: 70px;
}
.wd90 {
  width: 90px;
}
.wd93 {
  width: 93px;
}
.wd120 {
  width: 120px;
}
.wd130 {
  width: 130px;
}
.wd210 {
  width: 160px;
}
.wid {
  width: 160px;
}
.wid1 {
  width: 160px;
}
.wd230 {
  width: 230px;
}
.app-box {
  color: #333;
  .day-top {
    margin-bottom: 30px;
    color: #666;
    .top {
      float: left;
      width: 280px;
      margin-right: 20px;
    }
    .top_1 {
      width: 32%;
    }
    .top1 {
      float: left;
      width: 230px;
      margin-right: 20px;
    }
    .top2 {
      float: left;
      width: 240px;
      margin-right: 20px;
    }
    .top3 {
      float: left;
      width: 250px;
      margin-right: 20px;
    }
    .day-dropdown {
      float: right;
    }
  }
}
.baofe1 {
  width: 400px;
  .baofeiDetail {
    width: 49%;
    display: inline-block;
    div {
      padding: 8px;
      display: inline-block;
    }
  }
  a {
    display: block;
    width: 100%;
    color: #027dca;
    font-size: 13px;
    margin-top: 5px;
  }
  a:hover {
    text-decoration: underline;
  }
}
.unitbox {
  height: 40px;
  line-height: 40px;
  span {
    font-weight: 600;
  }
}
</style>